//
//  UMShareTypeViewController.m
//  UMSocialSDK
//
//  Created by wyq.Cloudayc on 11/16/16.
//  Copyright © 2016 UMeng. All rights reserved.
//

#import "UmengShareModule.h"
//#import <UShareUI/UShareUI.h>
#import <UMShare/UMShare.h>
#import <UMCommon/UMCommon.h>
#import <UShareUI/UShareUI.h>

@implementation UmengShareModule


RCT_EXPORT_MODULE();

//keys
RCT_EXPORT_METHOD(setKeys:(NSArray *)arr resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{

  RCTLogInfo(@"==setKeys===NSArray %@", arr);
  /* 打开日志 */
  [[UMSocialManager defaultManager] openLog:YES];
  @try {
    // dispatch_async(dispatch_get_main_queue(), ^{
        for(int i=0;i<arr.count;i++){
          NSDictionary  *dic=[arr objectAtIndex:i];
          //RCTLogInfo(@"===setKeys===dic %@", dic);
          //RCTLogInfo(@"==setKeys={name:%@,id:%@,key:%@}",[dic objectForKey:@"name"],[dic objectForKey:@"id"],[dic objectForKey:@"key"]);
          NSString *name=[dic objectForKey:@"name"];
          if([name isEqualToString:@"UMKEY"]){
            /* 设置友盟appkey */
        
           // [[UMSocialManager defaultManager] setUmSocialAppkey:[dic objectForKey:@"key"]];
          
            [UMConfigure setLogEnabled:YES];//设置打开日志
            [UMConfigure initWithAppkey:[dic objectForKey:@"key"] channel:nil];
          // [UMConfigure setLogEnabled:YES];//设置打开日志
          // [UMConfigure initWithAppkey:@"Your appkey" channel:@"App Store"];
            
          }else if([name isEqualToString:@"QQ"]){
            /* 设置分享到QQ互联的appID
             * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
             */
            [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:[dic objectForKey:@"id"]/*设置QQ平台的appID*/  appSecret:[dic objectForKey:@"key"] redirectURL:@"http://mobile.umeng.com/social"];
          }else if([name isEqualToString:@"WEIXIN"]){
            /* 设置微信的appKey和appSecret */
            [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:[dic objectForKey:@"id"] appSecret:[dic objectForKey:@"key"] redirectURL:@"http://mobile.umeng.com/social"];
          }
        }
      //设置用户自定义的平台
      [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),
                                                 @(UMSocialPlatformType_WechatTimeLine),
                                               //  @(UMSocialPlatformType_WechatFavorite),
                                                 @(UMSocialPlatformType_QQ),
                                                 @(UMSocialPlatformType_Qzone),
//                                                 @(UMSocialPlatformType_Sina),
//                                                 @(UMSocialPlatformType_TencentWb),
//                                                 @(UMSocialPlatformType_AlipaySession),
//                                                 @(UMSocialPlatformType_DingDing),
//                                                 @(UMSocialPlatformType_Renren),
//                                                 @(UMSocialPlatformType_Douban),
//                                                 @(UMSocialPlatformType_Sms),
//                                                 @(UMSocialPlatformType_Email),
//                                                 @(UMSocialPlatformType_Facebook),
//                                                 @(UMSocialPlatformType_FaceBookMessenger),
//                                                 @(UMSocialPlatformType_Twitter),
//                                                 @(UMSocialPlatformType_LaiWangSession),
//                                                 @(UMSocialPlatformType_LaiWangTimeLine),
//                                                 @(UMSocialPlatformType_YixinSession),
//                                                 @(UMSocialPlatformType_YixinTimeLine),
//                                                 @(UMSocialPlatformType_YixinFavorite),
//                                                 @(UMSocialPlatformType_Instagram),
//                                                 @(UMSocialPlatformType_Line),
//                                                 @(UMSocialPlatformType_Whatsapp),
//                                                 @(UMSocialPlatformType_Linkedin),
//                                                 @(UMSocialPlatformType_Flickr),
//                                                 @(UMSocialPlatformType_KakaoTalk),
//                                                 @(UMSocialPlatformType_Pinterest),
//                                                 @(UMSocialPlatformType_Tumblr),
//                                                 @(UMSocialPlatformType_YouDaoNote),
//                                                 @(UMSocialPlatformType_EverNote),
//                                                 @(UMSocialPlatformType_GooglePlus),
//                                                 @(UMSocialPlatformType_Pocket),
//                                                 @(UMSocialPlatformType_DropBox),
//                                                 @(UMSocialPlatformType_VKontakte),
//                                                 @(UMSocialPlatformType_UserDefine_Begin+1),
                                                 ]];
       resolve(@"0000");
//    });
    
  } @catch (NSException *exception) {
    reject(@"0001",nil,nil);
    RCTLogInfo(@"====setKeys=exception %@", exception);
  }

}

//share
RCT_EXPORT_METHOD(share:(NSDictionary *) map resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){

  //NSLog(@"==share={cmd:%@,url:%@,text:%@},title:%@,icon:%@,imageurl:%@,videourl:%@,musicurl:%@}",[map objectForKey:@"cmd"],[map objectForKey:@"url"],[map objectForKey:@"text"],[map objectForKey:@"icon"],[map objectForKey:@"imageurl"],[map objectForKey:@"videourl"],[map objectForKey:@"musicurl"],[map objectForKey:@"title"]);
  
  RCTLogInfo(@"==share===map %@", map);
  
//  Log.i("===setSharePlatforms","=======map:"+map);
//  final   String cmd= map.getString("cmd");// 分享类型
//  final   String url = map.getString("url");//"http://mobile.umeng.com/social";
//  final   String text = map.getString("text");//"欢迎使用【友盟+】社会化组件U-Share，SDK包最小，集成成本最低，助力您的产品开发、运营与推广";
//  final   String title = map.getString("title");//"【友盟+】社会化组件U-Share";
//  final   String icon = map.getString("icon"); // http://www.ecduo.cn/static/images/index/edo_hico_03.jpg
  //        final   String imageurl = map.getString("imageurl");//"https://mobile.umeng.com/images/pic/home/social/img-1.png";
  //        final   String videourl = map.getString("videourl");//"http://video.sina.com.cn/p/sports/cba/v/2013-10-22/144463050817.html";
  //        final   String musicurl = map.getString("musicurl");//"http://music.huoxing.com/upload/20130330/1364651263157_1085.mp3";
  
  @try {
    dispatch_async(dispatch_get_main_queue(), ^{
      
      int cmd=[[map objectForKey:@"cmd"] intValue];
      
      [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        if(cmd==1){ //网页分享
          UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[map objectForKey:@"text"] descr:[map objectForKey:@"title"] thumImage:[map objectForKey:@"icon"]];
          shareObject.webpageUrl = [map objectForKey:@"url"];//UMS_WebLink;
          //分享消息对象设置分享内容对象
          messageObject.shareObject = shareObject;
         // RCTLogInfo(@"==share===cmd=1 %@", shareObject);
        }else if(cmd==2){//图片分享
          UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
          shareObject.thumbImage = [map objectForKey:@"icon"];//UMS_THUMB_IMAGE;
          [shareObject setShareImage:[map objectForKey:@"imageurl"]];//UMS_IMAGE];
           messageObject.shareObject = shareObject;
        }else if(cmd==3){
          UMShareMusicObject *shareObject = [UMShareMusicObject shareObjectWithTitle:[map objectForKey:@"title"] descr:[map objectForKey:@"text"] thumImage:[map objectForKey:@"icon"]];
          //设置音乐网页播放地址
          shareObject.musicUrl = [map objectForKey:@"url"];//;@"http://c.y.qq.com/v8/playsong.html?songid=108782194&source=yqq#wechat_redirect";
          shareObject.musicDataUrl = [map objectForKey:@"musicurl"];//@"http://music.huoxing.com/upload/20130330/1364651263157_1085.mp3";
          //分享消息对象设置分享内容对象
          messageObject.shareObject = shareObject;
        }else if(cmd==4){
          UMShareVideoObject *shareObject = [UMShareVideoObject shareObjectWithTitle:[map objectForKey:@"title"] descr:[map objectForKey:@"text"] thumImage:[map objectForKey:@"icon"]];
          //设置视频网页播放地址
          shareObject.videoUrl = [map objectForKey:@"videourl"];//@"http://video.sina.com.cn/p/sports/cba/v/2013-10-22/144463050817.html";
          //分享消息对象设置分享内容对象
          messageObject.shareObject = shareObject;
        }else if(cmd==5){
          return;
        }else if(cmd==6){
          messageObject.text =  [map objectForKey:@"text"];//UMS_Text;
          //创建图片内容对象
          UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
          shareObject.thumbImage = [UIImage imageNamed:@"icon"];
          shareObject.shareImage = [UIImage imageNamed:@"logo"];
          //分享消息对象设置分享内容对象
          messageObject.shareObject = shareObject;
        }
        
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
          if (error) {
            RCTLogInfo(@"==shareToPlatform===error %@", error);
            UMSocialLogInfo(@"===************Share fail with error %@*********",error);
            reject(@"0002",nil,error);
          }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
              UMSocialShareResponse *resp = data;
              RCTLogInfo(@"==shareToPlatform==={result:%@,result2:%@}", resp.message,resp.originalResponse);
              //分享结果消息
              //UMSocialLogInfo(@"===response message is %@",resp.message);
              //第三方原始返回的数据
             // UMSocialLogInfo(@"===response originalResponse data is %@",resp.originalResponse);
            }else{
              RCTLogInfo(@"===share===result:%@",data);
              //UMSocialLogInfo(@"===response data is %@",data);
            }
            resolve(@"0000");
          }
        }];
      }];
    });
  } @catch (NSException *exception) {
    reject(@"0001",nil,nil);
    RCTLogInfo(@"====share=error %@", exception);
  }

}


//分享到小程序
RCT_EXPORT_METHOD(shareXCX:(NSDictionary *) map resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
  RCTLogInfo(@"==shareXCX===map %@", map);
   NSLog(@"==shareXCX={cmd:%@,url:%@,text:%@,title:%@,icon:%@,imageurl:%@,xcx_id:%@,path:%@}",[map objectForKey:@"cmd"],[map objectForKey:@"url"],[map objectForKey:@"text"],[map objectForKey:@"title"],[map objectForKey:@"icon"],[map objectForKey:@"imageurl"],[map objectForKey:@"xcx_id"],[map objectForKey:@"path"]);
  @try{
    dispatch_async(dispatch_get_main_queue(), ^{
     
      //创建分享消息对象
      UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
      UMShareMiniProgramObject *shareObject = [UMShareMiniProgramObject shareObjectWithTitle:[map objectForKey:@"title"]/*@"小程序标题"*/ descr:[map objectForKey:@"text"]/*@"小程序内容描述"*/ thumImage:[UIImage imageNamed:[map objectForKey:@"icon"]]];
      shareObject.webpageUrl = [map objectForKey:@"url"]/*@"兼容微信低版本网页地址"*/;
      shareObject.userName = [map objectForKey:@"xcx_id"]/*@"小程序username，如 gh_3ac2059ac66f"*/;
      shareObject.path = [map objectForKey:@"path"]/*@"小程序页面路径，如 pages/page10007/page10007"*/;
      
      NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[map objectForKey:@"imageurl"]]];
      UIImage * image = [UIImage imageWithData:data];
      shareObject.hdImageData=UIImageJPEGRepresentation(image, 0.1);
      shareObject.thumbImage=[UmengShareModule imageWithImage:[[UIImage alloc]initWithData:data] scaledToSize:CGSizeMake(500, 400)];
      
      messageObject.shareObject = shareObject;
      shareObject.miniProgramType = UShareWXMiniProgramTypeRelease; // 可选体验版和开发板
      
      //调用分享接口
      [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
        if (error) {
          RCTLogInfo(@"==shareToPlatform===error %@", error);
          UMSocialLogInfo(@"===************Share fail with error %@*********",error);
          reject(@"0002",nil,error);
        }else{
          if ([data isKindOfClass:[UMSocialShareResponse class]]) {
            UMSocialShareResponse *resp = data;
            RCTLogInfo(@"==shareToPlatform==={result:%@,result2:%@}", resp.message,resp.originalResponse);
            //分享结果消息
            //UMSocialLogInfo(@"===response message is %@",resp.message);
            //第三方原始返回的数据
            // UMSocialLogInfo(@"===response originalResponse data is %@",resp.originalResponse);
          }else{
            RCTLogInfo(@"===share===result:%@",data);
            //UMSocialLogInfo(@"===response data is %@",data);
          }
          resolve(@"0000");
        }

      }];
      
    });
    
  }@catch(NSException *exception){
    reject(@"0001",nil,nil);
    RCTLogInfo(@"====shareXCX=error %@", exception);
  }
}

//
//图片压缩(尺寸）
+ (UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize{
  UIGraphicsBeginImageContext(newSize);
  [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
  UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return newImage;
}


//login
RCT_EXPORT_METHOD(login:(NSString *) name resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{

    RCTLogInfo(@"====login= {name:%@}", name);
    int i=-2;
    if([name isEqualToString:@"QQ"]){
      i=4;
    }else if([name isEqualToString:@"WEIXIN"]){
      i=1;
    }
 
    if(i==-2){

      reject(@"0001",@"param name error",nil);
      return ;
    }
  
   [[UMSocialManager defaultManager] getUserInfoWithPlatform:i currentViewController:nil completion:^(id result, NSError *error) {
    
      UMSocialUserInfoResponse *resp = result;
     
     if(error){
       
           RCTLogInfo(@"====取消登录 %@", error);
           reject(@"0001",nil,nil);
     
     }else{
    
      RCTLogInfo(@"==login=result: %@", result);
      // 第三方登录数据(为空表示平台未提供)
      // 授权数据
      RCTLogInfo(@" uid: %@", resp.uid);
      RCTLogInfo(@" openid: %@", resp.openid);
      RCTLogInfo(@" accessToken: %@", resp.accessToken);
      RCTLogInfo(@" refreshToken: %@", resp.refreshToken);
      RCTLogInfo(@" expiration: %@", resp.expiration);
      // 用户数据
      RCTLogInfo(@" name: %@", resp.name);
      RCTLogInfo(@" iconurl: %@", resp.iconurl);
      RCTLogInfo(@" gender: %@", resp.gender);
      
      // 第三方平台SDK原始数据
      RCTLogInfo(@" originalResponse: %@", resp.originalResponse);
     
      resolve(@{@"uid": resp.uid, @"openid": resp.openid,@"accessToken":resp.accessToken,@"expiration":resp.expiration,@"name":name,@"iconurl":resp.iconurl,@"gender":resp.gender,@"data":resp.originalResponse});
     }
     
  }];
  
  
}




@end
